// 订单管理 API（收货开票）
import request from "@/utils/request";
import type { ApiResponse, PageResult } from "@/types/api";
import type {
  Order,
  OrderCreateParams,
  OrderUpdateParams,
  OrderQueryParams,
  OrderAssignRequest,
} from "@/types/order";

/**
 * 创建订单（收货开票）
 */
export function createOrder(data: OrderCreateParams) {
  return request<ApiResponse<Order>>({
    url: "/tenant/order",
    method: "post",
    data,
  });
}

/**
 * 获取订单列表（分页）
 */
export function getOrderList(params: OrderQueryParams) {
  return request<ApiResponse<PageResult<Order>>>({
    url: "/tenant/order/list",
    method: "get",
    params,
  });
}

/**
 * 获取订单详情
 */
export function getOrderById(id: number) {
  return request<ApiResponse<Order>>({
    url: `/tenant/order/${id}`,
    method: "get",
  });
}

/**
 * 更新订单
 */
export function updateOrder(id: number, data: OrderUpdateParams) {
  return request<ApiResponse<Order>>({
    url: `/tenant/order/${id}`,
    method: "put",
    data,
  });
}

/**
 * 删除订单
 */
export function deleteOrder(id: number) {
  return request<ApiResponse<null>>({
    url: `/tenant/order/${id}`,
    method: "delete",
  });
}

/**
 * 取消订单
 */
export function cancelOrder(
  id: number,
  data: { cancelReason: string; detail: string }
) {
  return request<ApiResponse<null>>({
    url: `/tenant/order/${id}/cancel`,
    method: "post",
    data,
  });
}

/**
 * 更新订单状态
 */
export function updateOrderStatus(id: number, status: string) {
  return request<ApiResponse<null>>({
    url: `/tenant/order/${id}/status`,
    method: "post",
    params: { status },
  });
}

/**
 * 分配订单（只分配司机，用于取货）
 * 车辆分配留到后续运单装车功能
 */
export function assignOrder(id: number, data: OrderAssignRequest) {
  return request<ApiResponse<null>>({
    url: `/tenant/order/${id}/assign`,
    method: "post",
    data,
  });
}

/**
 * 批量装车
 */
export function orderLoad(data: {
  ids: number[];
  vehicleId?: number;
  vehicleNo?: string;
  driverName?: string;
  driverPhone?: string;
  remark?: string;
  loadedAt?: string;
}) {
  return request<ApiResponse<Record<string, any>>>({
    url: "/tenant/order/load",
    method: "post",
    data,
  });
}

/**
 * 批量卸车
 */
export function orderUnload(data: { ids: number[] }) {
  return request<ApiResponse<Record<string, any>>>({
    url: "/tenant/order/unload",
    method: "post",
    data,
  });
}

/**
 * 分配送货司机（用于送货上门的订单）
 */
export function assignDeliveryDriver(
  id: number,
  data: { deliveryDriverId: number }
) {
  return request<ApiResponse<null>>({
    url: `/tenant/order/${id}/assign-delivery-driver`,
    method: "post",
    data,
  });
}

/**
 * 取消送货（清除送货司机，订单状态恢复为已到站）
 */
export function cancelDelivery(id: number) {
  return request<ApiResponse<null>>({
    url: `/tenant/order/${id}/cancel-delivery`,
    method: "post",
  });
}
